// 扩展 day.js 的插件
dayjs.extend(dayjs_plugin_utc)
dayjs.extend(dayjs_plugin_timezone)

const apiModulesPath = '/api/modules/'

async function getModules() {
	try {
		const response = await fetch(apiModulesPath + 'get')

		const result = await response.json()

		const { code, msg, data } = result

		if (code !== 200) {
			showNotify(msg, 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}

		const { friends_maxLength, limitAddFriendForm } = data
		
		$('#web_site_friends_maxLength').val(friends_maxLength)
		$('#web_site_limitAddFriendForm').val(limitAddFriendForm)
	} catch (error) {
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
		console.error('Error fetching modules:', error)
	}
}

getModules()

$('#friendsForm').on('submit', async function (e) {
	e.preventDefault()

	const formArrayInfo = $(this).serializeArray()
	let batchData = []

	$.each(formArrayInfo, function (_index, item) {
		batchData.push({
			module: item.name,
			xf_values: item.value || null
		})
	})

	const size = batchData.length - 1

	batchData.forEach(async (item, i) => {
		const jsonStr = JSON.stringify(item)
		
		try {
			const response = await $.ajax({
				url: apiModulesPath + 'set',
				type: 'POST',
				data: jsonStr,
				contentType: 'application/json'
			})
	
			const { code, msg } = response
			
			if (code !== 200) {
				showNotify(msg, 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
				return
			}
			if (i === size) {
				showNotify(msg, 'success', 5000, 'mdi mdi-emoticon-happy', 'top', 'right')
				return
			}
		} catch (error) {
			showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
			console.error('服务器有误: ', error)
		}
	})
})

const getFriendsShow = async (api, callback) => {
	try {
		const response = await fetch(api)
		const data = await response.json()
		callback(data)
	} catch (error) {
		console.error('Error fetching friends:', error)
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
	}
}

// 显示的dom
const $ShowLinksTable = $('#ShowLinksTable')
const $showPaginationDom = $('#showPaginationDom')

const apiPath = '/api/friends/'

let page = 1
let totalPage = 1 // 初始总页数
const pageSize = 10

function getFriendsFn(pageNum = 1) {
	$ShowLinksTable.html('加载中...')
	$showPaginationDom.html('加载中...')

	const getFriendsShowApi = apiPath + `get?isShow=1&page=${pageNum}&pageSize=${pageSize}`
	getFriendsShow(getFriendsShowApi, async function (result) {
		const { code, msg, data } = result
		if (code !== 200) {
			showNotify(msg, 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}

		let tr = ''
		data.data.forEach(item => {
			const chinaTime = dayjs(item.commitTime).tz('Asia/Shanghai')
			const formattedTime = chinaTime.format('YYYY年MM月DD日 HH:mm:ss')
			tr += `
			<tr class="text-center align-middle">
				<td>${item.id}</td>
				<td>${item.name}</td>
				<td>${item.introduced}</td>
				<td><a href="${item.link}" target="_blank" rel="noopener noreferrer">${item.link}</a></td>
				<td>${item.qq}</td>
				<td style="text-align: center; height: 100px;">
					${item.img ? `<img class="lazyload" data-src="${item.img}" style="width: 100px; height: auto;">` : '默认'}
				</td>
				<td>${item.ip}</td>
				<td>${formattedTime}</td>
				<td>
					<div class="btn-group btn-group-sm">
						<a
							class="btn btn-default"
							href="JavaScript:;"
							data-bs-toggle="tooltip"
							title="编辑"
							onclick="set(${item.id}, '${item.name}', '${item.introduced}', '${item.link}', '${item.qq}', '${item.img ? item.img : ''}')"
						><i class="mdi mdi-pencil"></i></a>
						<a class="btn btn-default" href="JavaScript:;" data-bs-toggle="tooltip" title="移除" onclick="del(${item.id})"><i class="mdi mdi-window-close"></i></a>
					</div>
				</td>
			</tr>
			`
		})

		$ShowLinksTable.html(tr)
		// 执行懒加载
		$('.lazyload').lazyload({
			root: null,
			rootMargin: '100px',
			threshold: 0
		})

		// 渲染工具
		renderTooltip()

		// 计算总页数
		totalPage = data.total && data.total > 0 ? Math.ceil(data.total / pageSize) : 1

		// 更新分页按钮
		renderPagination(pageNum, totalPage)
	})
}

// 获取数据的第一页
getFriendsFn(page)

// 渲染分页按钮
function renderPagination(currentPage, totalPage) {
	let pageHtml = ''
	$showPaginationDom.html('加载中...')

	// 上一页
	pageHtml += `<li class="page-item ${currentPage === 1 || totalPage === 0 ? 'disabled' : ''}">
		<a class="page-link" href="javascript:void(0);" onclick="selectPageNumber(${currentPage - 1})">上一页</a>
	</li>`

	if (totalPage > 10) {
		// 下一页
		pageHtml += `<li class="page-item ${currentPage === totalPage || totalPage === 0 ? 'disabled' : ''}">
			<a class="page-link" href="javascript:void(0);" onclick="selectPageNumber(${currentPage + 1})">下一页</a>
		</li>`
	} else {
		// 页码按钮
		for (let i = 1; i <= totalPage; i++) {
			pageHtml += `<li class="page-item ${currentPage === i ? 'active' : ''}">
				<a class="page-link" href="javascript:void(0);" onclick="selectPageNumber(${i})">${i}</a>
			</li>`
		}

		// 下一页
		pageHtml += `<li class="page-item ${currentPage === totalPage || totalPage === 0 ? 'disabled' : ''}">
			<a class="page-link" href="javascript:void(0);" onclick="selectPageNumber(${currentPage + 1})">下一页</a>
		</li>`

	}

	$showPaginationDom.html(pageHtml)
}

// 选择页数
function selectPageNumber(num) {
	if (num < 1 || num > totalPage || totalPage === 0) {
		return
	}
	page = num
	getFriendsFn(page)
}

// 新增
function add() {
	$.confirm({
		title: '新增友链',
		type: 'blue',
		animation: 'scale',
		draggable: true,
		content: `
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">名称</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-name" placeholder="请输入友链名称" class="form-control" autocomplete="off">
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">介绍</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-introduced" placeholder="请输入友链介绍" class="form-control" autocomplete="off">
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">网址</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-link" placeholder="请输入友链网址" class="form-control" autocomplete="off">
				</div>
				<small class="form-text">域名前面一定要带http://或者https://</small>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">QQ</label>
				<div class="input-group">
					<input autofocus="" type="number" id="input-qq" placeholder="请输入友链QQ" class="form-control" autocomplete="off">
				</div>
				<small class="form-text">网站联系QQ</small>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">网站图片</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-img" placeholder="请输入友链图片" class="form-control" autocomplete="off">
					<button class="btn btn-default uploadBtn" type="button"><span>上传图片</span><input type="file" accept="image/*" class="fileInput" onchange="handleFileSelect(event)"></button>
				</div>
				<small class="form-text">网站链接头像(选填, 不填写的话默认获取qq头像)</small>
			</div>
		`,
		buttons: {
			submit: {
				text: '提交',
				btnClass: 'btn-primary',
				action: function () {
					let that = this

					const name = that.$content.find('#input-name').val()
					const introduced = that.$content.find('#input-introduced').val()
					const link = that.$content.find('#input-link').val()
					const qq = that.$content.find('#input-qq').val()
					const img = that.$content.find('#input-img').val()

					const data = {
						name,
						introduced,
						link,
						qq,
						img: img || null,
						isShow: '1'
					}
					if (!$.trim(name) || !$.trim(introduced) || !$.trim(link) || !$.trim(qq)) {
						$.alert({
							title: '',
							content: '参数不得为空',
							type: 'orange'
						})
						return false
					}

					$.ajax({
						url: apiPath + 'add',
						type: 'POST',
						data,
						success: function (response) {
							const { code, msg } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'orange'
								})
								return
							}
							$.alert({
								title: '',
								content: '添加成功',
								type: 'green'
							})
							getFriendsFn(page)
						}
					})
				}
			},
			'取消': function () { }
		}
	})
}

// 更新
function set(id, name, introduced, link, qq, img) {	
	$.confirm({
		title: `更新友链`,
		type: 'blue',
		animation: 'scale',
		draggable: true,
		content: `
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">名称</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-name" value="${name}" placeholder="请输入友链名称" class="form-control" autocomplete="off">
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">介绍</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-introduced" value="${introduced}" placeholder="请输入友链介绍" class="form-control" autocomplete="off">
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">网址</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-link" value="${link}" placeholder="请输入友链网址" class="form-control" autocomplete="off">
				</div>
				<small class="form-text">域名前面一定要带http://或者https://</small>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">QQ</label>
				<div class="input-group">
					<input autofocus="" type="number" id="input-qq" value="${qq}" placeholder="请输入友链QQ" class="form-control" autocomplete="off">
				</div>
				<small class="form-text">网站联系QQ</small>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">网站图片</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-img" value="${img}" placeholder="请输入友链图片" class="form-control" autocomplete="off">
					<button class="btn btn-default uploadBtn" type="button"><span>上传图片</span><input type="file" accept="image/*" class="fileInput" onchange="handleFileSelect(event)"></button>
				</div>
				<small class="form-text">网站链接头像(选填, 不填写的话默认获取qq头像)</small>
			</div>
		`,
		buttons: {
			submit: {
				text: '提交',
				btnClass: 'btn-primary',
				action: function () {
					let that = this

					const name = that.$content.find('#input-name').val()
					const introduced = that.$content.find('#input-introduced').val()
					const link = that.$content.find('#input-link').val()
					const qq = that.$content.find('#input-qq').val()
					const img = that.$content.find('#input-img').val()

					const data = {
						id,
						name,
						introduced,
						link,
						qq,
						img: img || null,
						isShow: '1'
					}
					if (!$.trim(name) || !$.trim(introduced) || !$.trim(link) || !$.trim(qq)) {
						$.alert({
							title: '',
							content: '参数不得为空',
							type: 'orange'
						})
						return false
					}

					$.ajax({
						url: apiPath + 'set',
						type: 'POST',
						data,
						success: function (response) {
							const { code, msg } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'orange'
								})
								return
							}
							$.alert({
								title: '',
								content: '更新成功',
								type: 'green'
							})
							getFriendsFn(page)
						}
					})
				}
			},
			'取消': function () { }
		}
	})
}

// 删除
function del(id) {
	$.confirm({
		title: `确定删除id为: ${id}的友链吗`,
		content: '确定删除吗?',
		type: 'red',
		animation: 'scale',
		draggable: true,
		buttons: {
			'确定': {
				btnClass: 'btn-danger',
				action: function () {
					$.ajax({
						url: apiPath + 'del' + `?id=${id}`,
						type: 'GET',
						success: function (response) {
							const { code, msg } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'red'
								})
								return
							}

							$.alert({
								title: '',
								content: msg,
								type: 'green'
							})

							getFriendsFn(page)
						}
					})
				}
			},
			'取消': function () {}
		}
	})
}

let hiddenPage = 1
let hiddenTotalPage = 1 // 初始总页数
const hiddenPageSize = 10

// 获取申请中dom
const $hiddenLinksTable = $('#hiddenLinksTable')
const $hiddenPaginationDom = $('#hiddenPaginationDom')

function getHiddenFriendsFn(pageNum = 1) {
	$hiddenLinksTable.html('加载中...')
	$hiddenPaginationDom.html('加载中...')

	const getFriendsShowApi = apiPath + `get?isShow=0&page=${pageNum}&pageSize=${hiddenPageSize}`
	getFriendsShow(getFriendsShowApi, async function (result) {
		const { code, msg, data } = result
		if (code !== 200) {
			showNotify(msg, 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}

		let tr = ''
		data.data.forEach(item => {
			const chinaTime = dayjs(item.commitTime).tz('Asia/Shanghai')
			const formattedTime = chinaTime.format('YYYY年MM月DD日 HH:mm:ss')
			tr += `
			<tr class="text-center align-middle">
				<td>${item.id}</td>
				<td>${item.name}</td>
				<td>${item.introduced}</td>
				<td><a href="${item.link}" target="_blank" rel="noopener noreferrer">${item.link}</a></td>
				<td>${item.qq}</td>
				<td style="text-align: center; height: 100px;">
					${item.img ? `<img class="lazyload" data-src="${item.img}" style="width: 100px; height: auto;">` : '默认'}
				</td>
				<td>${item.ip}</td>
				<td>${formattedTime}</td>
				<td>
					<div class="btn-group btn-group-sm">
						<a class="btn btn-default" href="JavaScript:;" data-bs-toggle="tooltip" title="通过" onclick="show(${item.id})"><i class="mdi mdi-check-bold"></i></a>
						<a class="btn btn-default" href="JavaScript:;" data-bs-toggle="tooltip" title="移除" onclick="delHidden(${item.id})"><i class="mdi mdi-window-close"></i></a>
					</div>
				</td>
			</tr>
			`
		})

		$hiddenLinksTable.html(tr)
		// 执行懒加载
		$('.lazyload').lazyload({
			root: null,
			rootMargin: '100px',
			threshold: 0
		})

		// 渲染工具
		renderTooltip()

		// 计算总页数
		hiddenTotalPage = data.total && data.total > 0 ? Math.ceil(data.total / hiddenPageSize) : 1

		// 更新分页按钮
		renderHiddenPagination(pageNum, hiddenTotalPage)
	})
}

// 获取数据的第一页
getHiddenFriendsFn(page)

// 渲染分页按钮
function renderHiddenPagination(currentPage, totalPage) {
	let pageHtml = ''
	$hiddenPaginationDom.html('加载中...')

	// 上一页
	pageHtml += `<li class="page-item ${currentPage === 1 || totalPage === 0 ? 'disabled' : ''}">
		<a class="page-link" href="javascript:void(0);" onclick="selectHiddenPageNumber(${currentPage - 1})">上一页</a>
	</li>`

	if (hiddenTotalPage > 10) {
		// 下一页
		pageHtml += `<li class="page-item ${currentPage === totalPage || totalPage === 0 ? 'disabled' : ''}">
			<a class="page-link" href="javascript:void(0);" onclick="selectHiddenPageNumber(${currentPage + 1})">下一页</a>
		</li>`
	} else {
		// 页码按钮
		for (let i = 1; i <= totalPage; i++) {
			pageHtml += `<li class="page-item ${currentPage === i ? 'active' : ''}">
				<a class="page-link" href="javascript:void(0);" onclick="selectHiddenPageNumber(${i})">${i}</a>
			</li>`
		}

		// 下一页
		pageHtml += `<li class="page-item ${currentPage === totalPage || totalPage === 0 ? 'disabled' : ''}">
			<a class="page-link" href="javascript:void(0);" onclick="selectHiddenPageNumber(${currentPage + 1})">下一页</a>
		</li>`
	}

	$hiddenPaginationDom.html(pageHtml)
}

// 选择页数
function selectHiddenPageNumber(num) {
	if (num < 1 || num > hiddenTotalPage || hiddenTotalPage === 0) {
		return
	}
	hiddenPage = num
	getHiddenFriendsFn(hiddenPage)
}

function show(id) {
	$.confirm({
		title: `确定通过为: ${id}的友链吗`,
		content: '显示在首页',
		type: 'green',
		animation: 'scale',
		draggable: true,
		buttons: {
			'确定': {
				btnClass: 'btn-success',
				action: function () {
					$.ajax({
						url: apiPath + `isShow?isShow=1&id=${id}`,
						type: 'GET',
						success: function (response) {
							const { code, msg } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'red'
								})
								return
							}

							$.alert({
								title: '',
								content: msg,
								type: 'green'
							})

							getHiddenFriendsFn(hiddenPage)
							getFriendsFn(page)
						}
					})
				}
			},
			'取消': function () {}
		}
	})
}

function delHidden(id) {
	$.confirm({
		title: `确定删除id为: ${id}的友链吗`,
		content: '确定删除吗?',
		type: 'red',
		animation: 'scale',
		draggable: true,
		buttons: {
			'确定': {
				btnClass: 'btn-danger',
				action: function () {
					$.ajax({
						url: apiPath + 'del' + `?id=${id}`,
						type: 'GET',
						success: function (response) {
							const { code, msg } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'red'
								})
								return
							}

							$.alert({
								title: '',
								content: msg,
								type: 'green'
							})

							getHiddenFriendsFn(hiddenPage)
						}
					})
				}
			},
			'取消': function () {}
		}
	})
}